package com.free.mini.gateway.utils;

import org.apache.commons.lang3.StringUtils;

/**
 * url通配符匹配
 */
public class PathWildcardMatchUtil {

    /**
     * 匹配, 通配符默认为 *
     *
     * @param str
     * @param pattern
     * @return
     */
    public static boolean wildcardMatch(String str, String pattern) {
        String[] regulars = StringUtils.split(pattern, ",");
        for (String reg : regulars) {
            if (wildcardMatch(reg, str, "*")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 通配符匹配
     *
     * @param pattern  正则
     * @param str      匹配路径
     * @param wildcard 通配符
     * @return boolean
     */
    public static boolean wildcardMatch(String pattern, String str, String wildcard) {
        if (StringUtils.isEmpty(pattern) || StringUtils.isEmpty(str)) {
            return false;
        }
        final boolean startWith = pattern.startsWith(wildcard);
        final boolean endWith = pattern.endsWith(wildcard);
        String[] array = StringUtils.split(pattern, wildcard);
        int currentIndex = -1;
        int lastIndex = -1;
        switch (array.length) {
            case 0:
                return true;
            case 1:
                currentIndex = str.indexOf(array[0]);
                if (startWith && endWith) {
                    return currentIndex >= 0;
                }
                if (startWith) {
                    return currentIndex + array[0].length() == str.length();
                }
                if (endWith) {
                    return currentIndex == 0;
                }
                return str.equals(pattern);
            default:
                for (String part : array) {
                    currentIndex = str.indexOf(part);
                    if (currentIndex > lastIndex) {
                        lastIndex = currentIndex;
                        continue;
                    }
                    return false;
                }
                return true;
        }
    }
}